// User/pages/Login/index.js
import {
    showToast
} from '@/utils/util'
import {
    fetchLogin
} from '@/services/login'
import {
    customNavigate
} from '@/utils/route'
const app = getApp();

Page({
    data: {
        paddingTop: app.globalData.STATUS_BAR_HEIGHT + app.globalData.NAVIGATE_BAR_HEIGHT,
        paddingBottom: app.globalData.IPHONE_BAR_HEIGHT,
        staticPrefix: app.globalData.STATIC_PREFIX,
        checked: false
    },
    onLoad(options) {
        // customNavigate({
        //     url: '/User/pages/Register/index',
        //     params: {
        //         token: 'cnm'
        //     }
        // })
    },
    onShow() {
        if (wx.getStorageSync('USER_AGREE_COMPACT') && wx.getStorageSync('USER_AGREE_PRIVACY')) {
            this.setData({
                checked: true
            })
        }
    },
    onNavigate(e) {
        customNavigate({
            url: e.currentTarget.dataset.path
        })
    },
    onCheck(e) {
        if (e.detail) {
            this.setData({
                checked: !wx.getStorageSync('USER_AGREE_COMPACT') || !wx.getStorageSync('USER_AGREE_PRIVACY') ? false : true
            })
        } else {
            this.setData({
                checked: false
            })
        }

    },
    onLogin() {
        if (!this.data.checked) {
            showToast('请阅读隐私政策与用户协议');
            return
        };
    },
    async getPhoneNumber(e) {
        if (!this.data.checked) return;
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
            
            try {
                const res = await fetchLogin({
                    code: e.detail.code
                });
                wx.setStorage({
                    key: 'userInfo',
                    data: res.data,
                    success() {
                        wx.switchTab({
                            url: '/pages/Home/index'
                        })
                    }
                })
            } catch (error) {
                const {
                    return_code,
                    return_msg
                } = error;
                if (return_msg.includes('用户不存在')) {
                    showToast('非平台用户，请先注册', () => {
                        const params = {
                            token: return_msg.split('**')[1]
                        }
                        customNavigate({
                            url: '/User/pages/Register/index',
                            params
                        })
                    })
                }
            }
        }
    }
})